import { ref, computed } from 'vue'
import { useSlidesStore, usePageParamsStore } from '@/store'
import message from '@/utils/message'
import { templateList } from '@/mocks/template/list'
import { fetchClearPPTMeta, fetchGetOnlinePPT } from '@/http/fetchCourseware'

// 业务逻辑：当切换模板时，会重新生成PPT
export default () => {
  const isRefresh = ref(false)
  const slidesStore = useSlidesStore()
  const pageParams = usePageParamsStore()
  const onlineDocId = computed(() => pageParams.getPageIdParam)
  const msgTxt = ref({
    success: '加载成功',
    fail: '加载失败'
  })
  
  /**
   * 重新渲染
   */
  async function refreshResourceware(): Promise<boolean> {
    // 没有 onlineDocId 就不进行后续操作
    if (!onlineDocId.value) return false
    isRefresh.value = true

    const rs = await fetchClearPPTMeta(onlineDocId.value)
    if (rs) {
      const res = await getResourceware()
      isRefresh.value = false
      return res
    }
    
    isRefresh.value = false
    return false
  }

  async function getResourceware(): Promise<boolean> {
    // 没有 onlineDocId 就不进行后续操作
    if (!onlineDocId.value) return false
    
    isRefresh.value = true

    const courseware = await fetchGetOnlinePPT(onlineDocId.value, pageParams.template || 'base')
    if (courseware) {
      const { slides, tempId, title } = courseware
    
      slidesStore.setSlides(slides)
      const curTemp = templateList.find(item => item.id === tempId)
    
      if (curTemp) {
        const { width, ratio } = curTemp.container
        slidesStore.setViewportSize(width)
        slidesStore.setViewportRatio(ratio)
      }
      if (title) {
        slidesStore.setTitle(title)
      }
      message.success(msgTxt.value.success)
      return true
    }
    
    message.error(msgTxt.value.fail)
    return false
    
  }

  return {
    isRefresh,
    templateList,
    refreshResourceware,
    getResourceware
  }
}